#include "/home/zhong/muduo/examples/protobuf/codec/dispatcher.h"
#include "/home/zhong/muduo/examples/protobuf/codec/codec.h"

#include "muduo/base/Logging.h"
#include "muduo/base/Mutex.h"
#include "muduo/base/CountDownLatch.h"
#include "muduo/base/Timestamp.h"

#include "muduo/net/TcpConnection.h"
#include "muduo/net/EventLoopThread.h"
#include "muduo/net/TcpClient.h"

#include "request.pb.h"

#include <iostream>
#include<unistd.h>
#include <string>

class Client
{
    typedef std::shared_ptr<muduo::net::TcpConnection> TcpConnectionPtr;
    typedef std::shared_ptr<zhong::AddResponse> AddResponsePtr;
    typedef std::shared_ptr<zhong::TranslateResponse> TranslateResponsePtr;

public:
    Client(const std::string server_ip, const int server_port)
        : _latch(1),
          _client(_loop_thread.startLoop(), muduo::net::InetAddress(server_ip, server_port), "Client"),
          _dispatcher(std::bind(&Client::onUnknownMessage, this, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3)),
          _codec(std::bind(&ProtobufDispatcher::onProtobufMessage, &_dispatcher, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3))
    {
        // 1.注册业务请求处理函数
        _dispatcher.registerMessageCallback<zhong::TranslateResponse>(std::bind(&Client::onTranslate,
                                                                                this,
                                                                                std::placeholders::_1,
                                                                                std::placeholders::_2,
                                                                                std::placeholders::_3));
        _dispatcher.registerMessageCallback<zhong::AddResponse>(std::bind(&Client::onAdd,
                                                                          this,
                                                                          std::placeholders::_1,
                                                                          std::placeholders::_2,
                                                                          std::placeholders::_3));

        // 2.设置消息回调函数
        _client.setMessageCallback(std::bind(&ProtobufCodec::onMessage, &_codec, std::placeholders::_1, std::placeholders::_2, std::placeholders::_3));
        _client.setConnectionCallback(std::bind(&Client::onConnection, this, std::placeholders::_1));   // 只要有链接就默认调用   
    }

    void connect()
    {
        _client.connect();  // Tcp客户端发起connect
        _latch.wait();      // epoll模式下进行等待IO
    }
    // 客户端的业务请求
    // 1.首先进行类内字段的设置
    // 2.接着通过协议处理器的send接口进行发送
    void Translate(const std::string &mesg)
    {
        zhong::TranslateRequest request;
        request.set_msg(mesg);
        SendRequest(request);   // 因为protobuf我们自定义的对象（类），最终就是Message类的一个子类
    }
    void Add(int num1, int num2)
    {
        zhong::AddRequest request;
        request.set_num1(num1);
        request.set_num2(num2);
        SendRequest(request);
    }

private:
    void SendRequest(const google::protobuf::Message &Mesg)
    {
        if(_conn->connected() == true)
        {
            _codec.send(_conn, Mesg);   // 应用层协议
        }
    } 
    void onUnknownMessage(const TcpConnectionPtr &conn, const MessagePtr &message, muduo::Timestamp)
    {
    }
    void onTranslate(const muduo::net::TcpConnectionPtr &conn, const TranslateResponsePtr &message, muduo::Timestamp)
    {
        std::cout<<"translate result: "<<message->msg()<<std::endl;
    }
    void onAdd(const muduo::net::TcpConnectionPtr &conn, const AddResponsePtr &message, muduo::Timestamp)
    {
        std::cout<<"add result = "<<message->result()<<std::endl;
    }
    void onConnection(const muduo::net::TcpConnectionPtr &conn)
    {
        if(conn->connected() == true)
        {
            _latch.countDown();
            _conn = conn;
        }
        else    
        {
            _conn.reset();
        }
    }

private:
    muduo::CountDownLatch _latch;             // 实现同步机制
    muduo::net::EventLoopThread _loop_thread; // 异步循环处理线程
    muduo::net::TcpClient _client;            // 客户端
    muduo::net::TcpConnectionPtr _conn;       // 客户端对应链接
    ProtobufDispatcher _dispatcher;           // 请求事件分发器
    ProtobufCodec _codec;                     // 协议处理器
};
int main()
{
    std::unique_ptr<Client> client = std::make_unique<Client>("127.0.0.1", 8080);
    client->connect();
    while(1)
    {
        std::cout<<"please select one service: [Add/Translate]";
        std::string service;
        std::cin>>service;
        if(service == "Add")
        {
            std::cout<<"please input two num: ";
            int num1, num2;
            std::cin>>num1>>num2;
            client->Add(num1, num2);
        }
        else if (service == "Translate")
        {
            std::cout<<"please input a word: ";
            std::string word;
            std::cin>>word;
            client->Translate(word);
        }
        else 
        {
            std::cout<<"illegal service"<<std::endl;
        }
        sleep(1);
    }
}